package cn.tedu.charging.cost.dao.repository.impl;

import cn.tedu.charging.common.uitls.JsonUitls;
import cn.tedu.charging.cost.dao.repository.CostRuleCacheRepository;
import cn.tedu.charging.cost.pojo.po.CostRulePO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

//计价缓存Repository
@Repository
public class CostRuleCacheRepositoryImpl implements CostRuleCacheRepository {

    private static final Logger log = LoggerFactory.getLogger(CostRuleCacheRepositoryImpl.class);
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public List<CostRulePO>  getCostRuleByStationId(Integer stationId) {
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String costRuleKey = "COST_RULE_KEY_" + stationId;
        Serializable serializable = valueOperations.get(costRuleKey);
        log.debug("从redis获取数据:{}",serializable);
        if (serializable !=null){
            return  getCostRulesPOS(serializable);
        }
        return null;
    }

    //序列化转为对象
    private List<CostRulePO> getCostRulesPOS(Serializable serializable){
        List<CostRulePO> costRulePOList = new ArrayList<>();
        List<LinkedHashMap<String,CostRulePO>> maplist = JsonUitls.fromJson(String.valueOf(serializable), List.class);
        for (LinkedHashMap<String, CostRulePO> map : maplist) {
            // LinkedHashMap<String, CostRulePO>  map={id=1, stationId=5, gunType=1, name=尖上午, startTime=8, endTime=12, powerFee=1.5, serviceFee=0.4}
            log.debug("map 转话为CpstRulePO 之前的值 map={}",map);
            //objectMapper.convertValue 将 LinkedHashMap<String, CostRulePO> 转化为 CostRulePO.class
            CostRulePO costRulePO = JsonUitls.convertValue(map, CostRulePO.class);
            costRulePOList.add(costRulePO);
        }
        return costRulePOList;
    }

    @Override
    public void saveCostRule(Integer stationId, List<CostRulePO> costRulePO) {
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String costRuleKey = "COST_RULE_KEY_"+stationId;
        String json = JsonUitls.toJson(costRulePO);
        valueOperations.set(costRuleKey,json);
    }


}
